<!--
  * 地点地图
  *
  * @Author:    骆伟林
  * @Date:      2025-10-21 17:51:27
-->
<template>
  <a-row :gutter="8" style="margin-bottom: 10px">
    <div style="display: flex; align-items: center">
      搜索地址：
      <table style="margin-right: 10px">
        <tr>
          <td>
            <a-input-search id="tipinput" v-model:value="address" placeholder="请输入地址" />
          </td>
        </tr>
      </table>
    </div>
    <a-button type="primary" style="margin: 0 10px" @click="drawMarker">开始标记位置</a-button>
    <a-button type="primary" style="margin-right: 10px" @click="clearDrawings">清空标记位置</a-button>
    <a-button type="primary" @click="confirmRegion" :disabled="!isMarkerValid">确定位置</a-button>
  </a-row>
  <div class="map-container">
    <!-- 地图容器 -->
    <div id="container" ref="mapContainer"></div>
  </div>
</template>
<script setup>
  import { ref, onMounted, onUnmounted, computed } from 'vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { message } from 'ant-design-vue';

  const emit = defineEmits(['getArea']);

  // 定义 props
  const props = defineProps({
    address: {
      type: String,
      default: '',
    },
    longitude: {
      type: Number,
      default: undefined,
    },
    latitude: {
      type: Number,
      default: undefined,
    },
    deviceId: {
      type: String,
      required: true,
    },
    latAndLon: {
      type: Array,
      default: () => [undefined, undefined],
    },
  });

  const address = ref('');
  let map = null;
  let mouseTool = null;
  let polygon = null; // 用于存储绘制的多边形
  let currentOverlay = null;
  let AMapInstance = null;
  let placeSearch = null; // 地点搜索实例
  let autoComplete = null; // 自动完成实例
  let marker = null; // 用于存储点标记

  // 初始化地图
  let initMap = () => {
    const container = document.getElementById('container');
    if (!container) {
      console.error('Map container div not exist');
      return;
    }
    window._AMapSecurityConfig = {
      securityJsCode: '8c81168d00a5521156969ba6f9302035',
    };

    AMapLoader.load({
      key: '8a22a89acfe4e990d7e50ed0862b3bc3', // 高德地图 Key
      version: '2.0',
      plugins: [
        'AMap.MouseTool',
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.HawkEye',
        'AMap.ControlBar',
        'AMap.Geometry',
        'AMap.AutoComplete',
        'AMap.PlaceSearch',
        'AMap.GeometryUtil',
      ],
    })
      .then((AMap) => {
        AMapInstance = AMap;
        map = new AMap.Map('container', {
          center: [116.397428, 39.90923], // 地图中心点
          zoom: 14,
          viewMode: '2D',
          pitch: 30,
          resizeEnable: true,
        });
        // 初始化鼠标工具
        mouseTool = new AMap.MouseTool(map);
        // 监听绘制完成事件
        mouseTool.on('draw', (event) => {
          if (event.obj instanceof AMap.Polygon) {
            polygon = event.obj;
            currentOverlay = event.obj;
          } else if (event.obj instanceof AMap.Marker) {
            if (marker) {
              map.remove(marker);
            }
            marker = event.obj;
            currentOverlay = event.obj;
          }
        });

        // 添加比例尺控件
        const scale = new AMap.Scale();
        map.addControl(scale);

        // 添加工具条控件
        const toolBar = new AMap.ToolBar({
          position: {
            top: '110px',
            right: '40px',
          },
        });
        map.addControl(toolBar);

        // 初始化自动完成服务
        autoComplete = new AMapInstance.AutoComplete({
          input: 'tipinput',
        });
        // 监听选择事件
        autoComplete.on('select', select);
        // 初始化地点搜索
        placeSearch = new AMapInstance.PlaceSearch({
          map: map,
        });
        if (props.longitude && props.latitude) {
          // 设置地图中心点
          map.setCenter([props.longitude, props.latitude]);
          map.setZoom(15);

          // 回显图标
          if (props.latitude !== undefined && props.longitude !== undefined) {
            addMarker(props.longitude, props.latitude);
          }
        }
      })
      .catch((e) => {
        console.error('地图加载失败:', e);
      });
  };
  // 处理选择
  const select = (e) => {
    if (e.poi && e.poi.adcode && e.poi.name) {
      const { adcode, name } = e.poi;
      placeSearch.setCity(adcode);
      placeSearch.search(name);
    }
  };
  // 清空绘制图像
  function clearDrawings() {
    if (marker) {
      map.remove(marker);
      marker = null;
      currentOverlay = null;
      emit('getArea', undefined, undefined);
    }
    isMarkerValid.value = false;
  }

  // 确定区域
  async function confirmRegion() {
    if (marker) {
      try {
        const position = marker.getPosition();
        //传给父组件经纬度
        emit('getArea', position.lng, position.lat);
        message.success(`已标记位置：经度 ${position.lng}，纬度 ${position.lat}`);
      } catch (e) {
        console.log(e);
        message.info(e);
      }
    } else {
      message.warning('请先绘制覆盖物');
    }
  }

  const isMarkerValid = ref(true);
  function drawMarker() {
    if (marker) {
      map.remove(marker);
      marker = null;
    }

    // 开启鼠标工具绘制点标记
    mouseTool.marker({
      cursor: 'crosshair',
      draggable: true,
    });

    // 监听地图点击事件
    map.off('click');
    map.on('click', (e) => {
      const { lng, lat } = e.lnglat;
      // 直接在点击位置添加标记点
      if (marker) {
        map.remove(marker);
      }
      marker = new AMapInstance.Marker({
        position: new AMapInstance.LngLat(lng, lat),
        title: '设备位置',
        draggable: false,
      });
      map.add(marker);
      isMarkerValid.value = true;
    });
  }

  // 添加点标记
  function addMarker(lng, lat) {
    if (marker) {
      map.remove(marker);
    }
    marker = new AMapInstance.Marker({
      position: new AMapInstance.LngLat(lng, lat),
      title: '设备位置',
      draggable: false,
    });
    map.add(marker);
    map.setCenter([lng, lat]);
    map.setZoom(15);
  }
  // 组件挂载时初始化地图
  onMounted(async () => {
    initMap();
  });

  // 组件卸载时销毁地图
  onUnmounted(() => {
    if (map) {
      map.destroy();
      map = null;
    }
  });
</script>

<style scoped>
  .map-container {
    position: relative;
    width: 100%;
    height: 60vh; /* 地图高度 */
  }

  #container {
    width: 100%;
    height: 100%; /* 地图容器占满父级 */
  }

  .toggle-button {
    position: absolute;
    top: 10px;
    left: 20px;
    display: flex;
    align-items: center;
  }

  .search-drawer {
    position: absolute;
    top: 5%;
    left: 0;
    width: 400px;
    height: 80%;
    background-color: white;
    box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
  }

  .tree-control {
    position: absolute;
    top: 0;
    right: 20px;
    z-index: 5;
  }
</style>
